<?php
/**
 *
 *@package 
 *@copyright Copyright (c) 2012-2014 Tuniu.com
 *@author huxiaomin 2012
 *@version 1.0
 */

class TCurl{

	/**
	 * @param string $url
	 * @param string or array $data
	 * @param int $time_out
	 */
    static public function post($url, $data,$time_out=0,$port=0){
    	try {
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		if ($time_out){
			curl_setopt($ch,CURLOPT_TIMEOUT,$time_out);
		}
		if ($port){
		    curl_setopt($ch,CURLOPT_PORT,$port);
		}
		
		$return = array();
		$return['data'] = curl_exec($ch);
		$error = curl_error($ch);
		$errno = curl_errno($ch);
		$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$return['error'] = "errno:{$errno},error:{$error},http_code:{$http_code}";
		curl_close($ch);
		if ($errno == 28 && preg_match('/Operation/i',$return['error'])){
			$return['success'] = 2;//超时
			$return['error'] = "访问超时:".$return['error'];
		}
		else if ($errno || $http_code >= 400){
		    $return['success'] = 0;
		    $return['error'] = "访问异常：".$return['error'];
		}
		else {
		    $return['success'] = 1;
		}
    	}catch (Exception $e){
    	    $return['success'] = 0;
    	    $return['error'] = "程序异常:".print_r($e, 1);
    	}
		return $return;
    }
    
    static public function postAsync($url,$post_arr,$time_out = 5){
    	try{
        $arr = parse_url($url);
        $arr['port'] || $arr['port'] = 80; 
        $fp = fsockopen($arr['host'],$arr['port'],$errno,$errstr,$time_out);
        if($fp) {
             $post_data = "";
             if($post_arr){
                 foreach ($post_arr as $k=>$v) {
                     $post_data .=rawurlencode($k).'='.rawurlencode($v).'&'; 
                 }
                    
                 $post_data = substr($post_data,0,-1);
             }
             $data_len = strlen($post_data);
                
             $arr['query'] && $arr['query'] = '?'.$arr['query'];
             $out = "POST ".$arr['path'].$arr['query']." HTTP/1.1\r\n";
             $out .= "Host: ".$arr['host']."\r\n";
             $out .= "Content-type:application/x-www-form-urlencoded\r\n";  
             $out .= "Connection: Close\r\n";
             $out .= "Content-Length:$data_len\r\n\r\n"; 
             $out .= $post_data."\r\n";
             fwrite($fp,$out);
             fclose($fp);
       }
       $return['success'] = $fp ? 1 : 0;
       $return['error'] = "errno:{$errno},error:{$errstr}";
    	}catch (Exception $e){
    	   $return['success'] = 0;
            $return['error'] = "程序异常:".print_r($e, 1);
    	}
       return $return;
    }
}

/**
 * function Curl_http($array, $timeout)
{
$res = array();
$mh = curl_multi_init(); //创建多个curl语柄
//var_dump($mh);exit;
$startime = getmicrotime();
//echo $startime;exit;
foreach($array as $k => $url)
{
$conn[$k] = curl_init($url);//创建一个curl 会话
//curl_setopt 设置一个cURL传输
curl_setopt($conn[$k], CURLOPT_TIMEOUT, $timeout); //设置超时时间
curl_setopt($conn[$k], CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');//在HTTP请求中包含一个"User-Agent: "头的字符串
curl_setopt($conn[$k], CURLOPT_MAXREDIRS, 7); //HTTp定向级别
curl_setopt($conn[$k], CURLOPT_HEADER, 0); //这里不要header，加块效率
// curl_setopt($conn[$k], CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
curl_setopt($conn[$k], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle ($mh, $conn[$k]);//向curl批处理会话中添加单独的curl句柄
} 
// 防止死循环耗死cpu 这段是根据网上的写法
do
{
$mrc = curl_multi_exec($mh, $active); //当无数据，active=true
} 
while ($mrc == CURLM_CALL_MULTI_PERFORM); //当正在接受数据时
while ($active and $mrc == CURLM_OK) // 当无数据时或请求暂停时，active=true
{
if (curl_multi_select($mh) != -1)
{
do
{
$mrc = curl_multi_exec($mh, $active);
} 
while ($mrc == CURLM_CALL_MULTI_PERFORM);
} 
} 
 
foreach ($array as $k => $url)
{
curl_error($conn[$k]);
$res[$k] = curl_multi_getcontent($conn[$k]); //获得返回信息
// var_dump($res[$k]);exit;
$header[$k] = curl_getinfo($conn[$k]); //返回头信息
//var_dump($header[$k]);exit;
curl_close($conn[$k]); //关闭语柄
curl_multi_remove_handle($mh , $conn[$k]); //释放资源
} 
 
curl_multi_close($mh);//关闭一组cURL句柄
$endtime = getmicrotime();
$diff_time = $endtime - $startime;
 
return array('diff_time' => $diff_time,
'return' => $res,
// 'header' => $header
);
// var_dump($da['return']);exit('000');
} 
// 计算当前时间
function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}*/
